package com.zj.easy.ui.dialog;

import android.util.Log;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 类描述:多弹窗显示管理
 * 只需将DialogBase,Push进队列中即可
 * DialogManager.getInstance().pushToQueue(BuildBean)
 */
public class DialogManager {

    private static final String TAG = "DialogManager";
    private static Queue<DialogBase> queue = new ConcurrentLinkedQueue<>(); //弹窗队列(线程安全)
    private static DialogManager mInstance;
    private DialogBase mDialogBase;

    public static DialogManager getInstance() {
        if (mInstance == null) {
            synchronized (DialogManager.class) {
                if (mInstance == null) {
                    mInstance = new DialogManager();
                }
            }
        }
        return mInstance;
    }

    public boolean isShowing() {
        if (mDialogBase != null) {
            mDialogBase.isShowing();
        }
        return false;
    }

    /**
     * 每次弹窗调用PushQueue方法
     *
     * @param dialogBase
     */
    public void pushToQueue(DialogBase dialogBase) {
        //添加到队列中
        if (dialogBase != null) {
            Log.e(TAG, "add..");
            queue.add(dialogBase);

            startNextIf();
        }
    }

    /**
     * 显示下一个弹窗任务
     */
    private void startNextIf() {
        //只有当前没有dialog正在展示,才能展示
        if (mDialogBase==null) {
            if (queue != null && queue.isEmpty()) {
                return;
            }
            //Todo 可在此处对弹窗进行排序
            oderDialog();
            mDialogBase = queue.poll();
            if (mDialogBase != null) {
                mDialogBase.show();
            } else {
                Log.e(TAG, "任务队列为空...");
            }
        }
    }

    public DialogBase getCurrentDialog() {
        return mDialogBase;
    }

    private void oderDialog() {


    }


    /**
     * 清除所有弹窗
     */
    public void clear() {
        queue.clear();
        if (mDialogBase != null) {
            mDialogBase.dismiss();
        }
        mDialogBase = null;
    }

    /**
     * 提供外部下一个任务的方法,在弹窗消失时候调用
     */
    public void nextTask() {
        mDialogBase = null;
        startNextIf();
        Log.e(TAG, "nextTask");
    }

}
